package com.tubi.maipiao3;

import java.util.concurrent.locks.ReentrantLock;

//线程继承Runnble 接口
public class Ticket implements Runnable {
    //票数
    public int ticket = 100;
    public Object obj = new Object();
    public ReentrantLock lock = new ReentrantLock();

    /*
    *
    *  同步代码块
    * synchronized(任意对象) {
            多条语句操作共享数据的代码
        }
    * */
    @Override
    public void run() {
        while (true) {
            try {
                lock.lock();
                if (ticket <= 0) {
                    break;
                } else {
                    Thread.sleep(10);
                    ticket--;
                    System.out.println(Thread.currentThread().getName() + "在买票，还剩下" + ticket + '张');
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();

            }
        }
    }
}
